﻿using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour {

	bool m_firstSession = true;
	bool m_playing = false;
	float m_score = 0f;
	float m_best = 0f;

	public GUIText m_scoreUI;
	public GUIText m_bestUI;
	public GUITexture m_cover;
	public Texture m_startTexture;
	public Texture m_retryTexture;
	public GUIText m_gameOverMessage;

	public TrackManager m_trackManager;

	void Start ()
	{
		//m_cover.gameObject.SetActive(false);
	}
	
	void Update ()
	{
		if (m_playing)
		{
			m_score += Time.deltaTime;
			m_scoreUI.text = m_score.ToString();

			if (m_best < m_score)
			{
				m_best = m_score;
				m_bestUI.text = m_best.ToString();
			}
		}
	}

	void OnGUI()
	{
		if (!m_playing)
		{
			if (m_firstSession)
			{
				if (GUI.Button(new Rect(Screen.width / 2f - m_startTexture.width / 2f, Screen.height / 2f - m_startTexture.height / 2f, m_startTexture.width, m_startTexture.height), m_startTexture, new GUIStyle()))
				{
					StartGame();
				}
			}
			else
			{
				if (GUI.Button(new Rect(Screen.width / 2f - m_retryTexture.width / 2f, Screen.height / 2f - m_retryTexture.height / 2f, m_retryTexture.width, m_retryTexture.height), m_retryTexture, new GUIStyle()))
				{
					RestartGame();
				}
			}
		}
	}

	public void RestartGame()
	{
		m_trackManager.ResetTracks();
		StartGame();
	}

	public void StartGame()
	{
		m_score = 0f;
		m_trackManager.StartTracks();
		m_playing = true;
		m_firstSession = false;
		m_cover.gameObject.SetActive(false);
		m_gameOverMessage.gameObject.SetActive(false);
	}

	public void Crashed()
	{
		m_playing = false;
		m_trackManager.StopTracks();
		m_cover.gameObject.SetActive(true);
		m_gameOverMessage.gameObject.SetActive(true);
	}
}
